package com.mp.approvalreq.servlet;

import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.Template;
import com.mp.approvalreq.entity.dto.TemplateRangeDTO;
import com.mp.approvalreq.service.ReadTemplateServicePrx;
import com.mp.approvalreq.util.ApprovalUtils;
import com.mp.approvalreq.util.ListHelper;
import com.mp.approvalreq.util.ServiceUtils;
import com.mp.user.entity.User;
import com.mp.user.service.UserServicePrx;
import com.mp.user.util.UserUtils;
import com.plusmoney.exception.RpcServerLogicalException;
import com.plusmoney.util.Utils;
import com.qq.tars.client.util.ServantUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 *  同一个审批类型多个模板共存,但是其适用范围互斥
 *
 *  修改模板时,传的是这个模板的id
 *  新建模板时,传的是0
 *
 */
@WebServlet("/getTemplateRange")
public class GetTemplateRange extends AbstractServlet {
		
	private static final Logger logger = LoggerFactory.getLogger(GetTemplateRange.class);
	
	private static final String DEFAULT_TYPE = "defaultType";
	private static final String TEMPLATEID = "templateId";
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			User user = getReqUser(req);
			
			Integer defaultType = getDefaultType(req);
			Integer templateId = getTemplateId(req);
			check(defaultType, templateId);
			
			ReadTemplateServicePrx readTemplateServicePrx = ServiceUtils.getReadTemplateServicePrx();
			List<TemplateRangeDTO> templateRangeDTOs = readTemplateServicePrx.getTemplatesRange(templateId, defaultType, user.getCompanyId());
				
			wrapTemplateRangDTOs(templateRangeDTOs, user.getCompanyId());
			
			returnResult(resp, templateRangeDTOs);
		} catch (Throwable e) {
			onThrowable(req, resp, e);
		}
	}
	
	private void returnResult(HttpServletResponse resp, List<TemplateRangeDTO> templateRangeDTOS) throws IOException {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", "0");
		jsonObject.put("res_info", "成功");
		jsonObject.put("item", templateRangeDTOS);
		
		logger.info(jsonObject.toJSONString());
		
		printJson(resp, jsonObject.toJSONString());
	}
	
	
	private void check(Integer defaultType, Integer templateId) {
		if (Utils.isNull(defaultType) || Utils.isNull(templateId)) {
			throw new RpcServerLogicalException(1, "参数错误");
		}
		
		if (defaultType < Template.EXPENSES || defaultType > Template.LEND_MONEY) {
			throw new RpcServerLogicalException(1, "参数错误");
		}
		
		logger.info("type:{} | templateId:{}", defaultType, templateId);
	}
	
	
	private void wrapTemplateRangDTOs(List<TemplateRangeDTO> templateRangeDTOS, Integer companyId) throws Throwable {
		UserServicePrx userService = ServantUtils.getObject(UserServicePrx.class);
		List<User> allUsers = userService.getAllNormalUserListWithAdmin(companyId);
		
		for (TemplateRangeDTO templateRangeDTO : templateRangeDTOS) {
			// 全公司
			if (ApprovalUtils.isAllCompanyRange(templateRangeDTO.getDepartmentIds())) {
				templateRangeDTO.setContactIdRange(ListHelper.getContactIds(allUsers));
			}
			
			// 指定人
			if (ApprovalUtils.isSpecificRange(templateRangeDTO.getDepartmentIds())) {
				List<User> users = getSameMultiUserByCompanyInfoId(templateRangeDTO.getCompanyInfoIdRange(), allUsers);
				templateRangeDTO.setContactIdRange(ListHelper.getContactIds(users));
			}
			
			// 指定部门和指定人
			if (ApprovalUtils.isSpecifiedDepts(templateRangeDTO.getDepartmentIds())) {
				List<User> users = new LinkedList<>();
				// 指定的部门可能没有人,同时有没有指定人的时候,companyInfoIdRange会为Null
				if (StringUtils.isNotEmpty(templateRangeDTO.getCompanyInfoIdRange())) {
					users.addAll(getSameMultiUserByCompanyInfoId(templateRangeDTO.getCompanyInfoIdRange(), allUsers));
				}
				List<User> deptUsers = userService.getUserListByDepartmentIds(companyId, templateRangeDTO.getDepartmentIds());
				// 指定部门所有身份
				users.addAll(getSameUserByCompanyInfoId(deptUsers, allUsers));
				users = UserUtils.uniqueUsersByContactId(users);
				
				templateRangeDTO.setContactIdRange(ListHelper.getContactIds(users));
			}
		}
	}
	
	
	private List<User> getSameMultiUserByCompanyInfoId(String companyInfoIdRange, List<User> allUsers) {
		Map<Integer, User> map = new HashMap<>();
		
		for (String companyInfoId : companyInfoIdRange.split(",")) {
			for (User allUser : allUsers) {
				if (companyInfoId.equals(allUser.getCompanyInfoId().toString())) {
					map.put(allUser.getContactId(), allUser);
				}
			}
		}
		
		return new ArrayList<>(map.values());
	}
	
	
	
	private List<User> getSameUserByCompanyInfoId(List<User> deptUsers, List<User> allUsers) {
		Map<Integer, User> map = new HashMap<>();
		
		for (User deptUser : deptUsers) {
			for (User allUser : allUsers) {
				if (deptUser.getCompanyInfoId().equals(allUser.getCompanyInfoId())) {
					map.put(allUser.getContactId(), allUser);
				}
			}
		}
		
		return new ArrayList<>(map.values());
	}


	private Integer getDefaultType(HttpServletRequest req) {
		Integer type;
		try {
			type = Integer.valueOf(req.getParameter(DEFAULT_TYPE));
		} catch (Throwable e) {
			throw new RpcServerLogicalException(1, "参数错误");
		}
		return type;
	}
	
	private Integer getTemplateId(HttpServletRequest req) {
		Integer templateId;
		try {
			templateId = Integer.valueOf(req.getParameter(TEMPLATEID));
		} catch (Throwable e) {
			throw new RpcServerLogicalException(1, "参数错误");
		}
		return templateId;
	}
}
